package com.valuegroup.smarttodo.ui.programme.curriculum;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.valuegroup.smarttodo.R;
import com.valuegroup.smarttodo.data.ServiceFactory;
import com.valuegroup.smarttodo.data.model.Curriculum;
import com.valuegroup.smarttodo.data.model.Event;
import com.valuegroup.smarttodo.data.model.Task;
import com.valuegroup.smarttodo.data.vo.CurriculumEventVo;
import com.valuegroup.smarttodo.plugins.pickdialog.DatePickDialog;
import com.valuegroup.smarttodo.plugins.pickdialog.OnSureLisener;
import com.valuegroup.smarttodo.plugins.pickdialog.bean.DateType;
import com.valuegroup.smarttodo.plugins.recyclerview.ItemTouchHelperAdapter;
import com.valuegroup.smarttodo.plugins.recyclerview.ItemTouchHelperViewHolder;
import com.valuegroup.smarttodo.ui.todo.task.detail.TaskDetailActivity;
import com.valuegroup.smarttodo.ui.todo.task.qucikadd.ChangeViewCallback;
import com.valuegroup.smarttodo.ui.todo.task.qucikadd.ExpansionCallback;
import com.valuegroup.smarttodo.ui.todo.task.qucikadd.QucikAddActivity;
import com.valuegroup.smarttodo.ui.todo.task.qucikadd.QucikAddEditText;
import com.valuegroup.smarttodo.ui.todo.task.qucikadd.QucikAddInputCheckRule;
import com.valuegroup.smarttodo.ui.todo.task.qucikadd.QuickAddEditorCallback;
import com.valuegroup.smarttodo.ui.todo.task.qucikadd.QuickAddHolder;
import com.valuegroup.smarttodo.util.AlertUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CurriculumOrderAdapter extends RecyclerView.Adapter implements ItemTouchHelperAdapter {

    private Context mContext;
    private RecyclerView recyclerView;
    private Curriculum curriculum;
    private Long curriculumId;
    private List<CurriculumEventVo> mDatas = new ArrayList<>();
    private static RefreshEventCountCallback refreshEventCountCallback;

    public CurriculumOrderAdapter(Context context, RecyclerView recyclerView, Long id) {
        this.mContext = context;
        this.recyclerView = recyclerView;
        refreshListData(id, true);
    }

    public void refreshListData(Long id, boolean isFrist) {
        this.curriculumId = id;
        curriculum = ServiceFactory.getInstance().getCurriculumService().getCurriculumDao().load(id);
        if (curriculum == null) {
            curriculum = ServiceFactory.getInstance().getCurriculumService().getDefaultCurriculum();
        }

        if (!isFrist) {
            // 用于刷新
            int previousSize = mDatas.size();
            this.mDatas.clear();
            notifyItemRangeRemoved(0, previousSize + START_COUNT + END_COUNT);
            this.mDatas.addAll(ServiceFactory.getInstance().getCurriculumService().findCurriculumEventForHome(id));
            notifyItemRangeInserted(0, getItemCount());
        } else {
            // 用于初始化
            this.mDatas.addAll(ServiceFactory.getInstance().getCurriculumService().findCurriculumEventForHome(id));
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
        if (viewType == TYPE_HEAD) {
            return new HeadHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_default_header, viewGroup, false));
        } else if (viewType == TYPE_CONTENT) {
            return new ItemViewHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_curriculum_manage, viewGroup, false));
        } else {
            return new ButtomHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_default_bottom, viewGroup, false));
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof ItemViewHolder) { // 内容
            ItemViewHolder myHolder = (ItemViewHolder) holder;
            final CurriculumEventVo item = mDatas.get(position - START_COUNT);
            myHolder.initData(item);
        }
    }

    @Override
    public int getItemViewType(int position) {
        int contentSize = getContentSize() + START_COUNT;
        if (position == 0) { // 头部
            return TYPE_HEAD;
        } else if (position == contentSize) { // 尾部
            return TYPE_BOTTOM;
        } else {
            return TYPE_CONTENT;
        }
    }

    @Override
    public int getItemCount() {
        return mDatas.size() + START_COUNT + END_COUNT;
    }

    public int getContentSize() {
        return mDatas.size();
    }

    public Context getmContext() {
        return mContext;
    }


    public void addItem(int position, CurriculumEventVo item) {

        item = ServiceFactory.getInstance().getCurriculumService().saveCurriculumEvent(item);
        mDatas.add(position, item);

        // 因添加了头尾布局，所以需要加上顶部
        notifyItemInserted(position + START_COUNT);
    }


    public void updateItem(int position, Event e) {
        mDatas.set(position - START_COUNT, CurriculumEventVo.convertEvent(e));
        notifyItemChanged(position, CurriculumEventVo.convertEvent(e));
    }

    public final static int START_COUNT = 1;
    public final static int END_COUNT = 1;

    public final static int TYPE_HEAD = 0;
    public final static int TYPE_CONTENT = 1;
    public final static int TYPE_BOTTOM = 2;

    @Override
    public void onItemMove(int fromPosition, int toPosition) {
        if (getItemViewType(fromPosition) != TYPE_CONTENT) {
            return;
        }

        if (fromPosition < toPosition) {
            for (int i = fromPosition - START_COUNT; i < toPosition - START_COUNT; i++) {
                Collections.swap(mDatas, i, i + 1);
            }
        } else {
            for (int i = fromPosition - START_COUNT; i > toPosition - START_COUNT; i--) {
                Collections.swap(mDatas, i, i - 1);
            }
        }
        notifyItemMoved(fromPosition, toPosition);
    }

    @Override
    public void onItemDismiss(int position, boolean isLeftSlide) {
        if (getItemViewType(position) != TYPE_CONTENT) {
            return;
        }

        CurriculumEventVo vo = mDatas.get(position - START_COUNT);

        if (isLeftSlide) {
            // 删除
            AlertUtils.dialog(getmContext(),
                    String.format(getmContext().getResources().getString(R.string.alt_del_goal_event), vo.getTitle()),
                    getmContext().getResources().getString(R.string.op_delete),
                    getmContext().getResources().getString(R.string.op_cancel),
                    (dialog, which) -> {
                        ServiceFactory.getInstance().getCurriculumService().delCurriculumEvent(vo.getId());
                        mDatas.remove(position - START_COUNT);
                        notifyItemRemoved(position);
                        notifyItemRangeChanged(0, getItemCount());
                        refreshEventCountCallback.refresh();
                    }, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            //notifyItemRangeChanged(0, getItemCount());
                            refreshListData(curriculumId, false);
                        }
                    });
        } else {
            // 快速排期

            if (ServiceFactory.getInstance().getEventService().eventIsJoinTask(vo.getId())) {
                if (vo.getFinish()) {
                    // 已排期事务如已完成，在移除时需要用户确认
                    AlertUtils.removeJoinDialog(getmContext(),
                            getmContext().getResources().getString(R.string.alt_remove_event_task),
                            (dialog, which) -> {
                                ServiceFactory.getInstance().getEventService().doRmoveJoinScheduleDelTask(vo.getId());
                                AlertUtils.showToast(getmContext(), R.string.alt_remove_join_task);
                                refreshListData(curriculumId, false);
                            }
                    );
                } else {
                    ServiceFactory.getInstance().getEventService().doRmoveJoinScheduleDelTask(vo.getId());
                    AlertUtils.showToast(getmContext(), R.string.alt_remove_join_task);
                }

            } else {
                ServiceFactory.getInstance().getEventService().doJoinScheduleAndCreateTask(vo.getId(), new Date());
                AlertUtils.showToast(getmContext(), R.string.alt_join_task);
            }
            //notifyItemRangeChanged(0, getItemCount());
            refreshListData(curriculumId, false);

            //平滑到操作项
            ((LinearLayoutManager) recyclerView.getLayoutManager()).scrollToPositionWithOffset(position, 0);
        }
    }


    // 中间的内容
    public class ItemViewHolder extends RecyclerView.ViewHolder implements ItemTouchHelperViewHolder {

        @BindView(R.id.labTitle)
        TextView labTitle;
        @BindView(R.id.rootLayout)
        LinearLayout rootLayout;
        @BindView(R.id.tagFinish)
        TextView tagFinish;
        @BindView(R.id.labScheduDt)
        TextView labScheduDt;
        @BindView(R.id.barSchedule)
        LinearLayout barSchedule;

        private CurriculumEventVo data;

        public void initData(CurriculumEventVo data) {
            this.data = data;
            labTitle.setText(data.getTitle());

            if (TextUtils.isEmpty(data.getScheduDt())) {
                labScheduDt.setVisibility(View.GONE);
                barSchedule.setVisibility(View.GONE);
            } else {
                labScheduDt.setVisibility(View.VISIBLE);
                labScheduDt.setText(data.getScheduDt());
                barSchedule.setVisibility(View.VISIBLE);
            }
            tagFinish.setVisibility(data.getFinish() ? View.VISIBLE : View.GONE);
        }

        public ItemViewHolder(final View v) {
            super(v);
            ButterKnife.bind(this, v);
        }

        @OnClick({R.id.labTitle, R.id.labScheduDt})
        public void onViewClicked(View view) {
            switch (view.getId()) {
                case R.id.labTitle:

                    if (curriculum.getId() == null || curriculum.getId() == 0) {
                        AlertUtils.showToast(itemView.getContext(), R.string.need_insert_content);
                        return;
                    }

                    QucikAddActivity.openEditorNoRepeatAndSetFinish(
                            getmContext(),
                            new QuickAddEditorCallback() {
                                @Override
                                public void onCancel() {
                                    Event e = ServiceFactory.getInstance().getEventService().getEventDao().load(data.getId());
                                    updateItem(getAdapterPosition(), e);
                                }

                                @Override
                                public void onSubmit(String title) {
                                    if (TextUtils.isEmpty(title)) {
                                        return;
                                    }

                                    Event e = ServiceFactory.getInstance().getEventService().updateEventTitle(data.getId(), title);
                                    updateItem(getAdapterPosition(), e);
                                }

                                @Override
                                public void onAttached(final ViewGroup rootView) {
                                    QucikAddEditText etContent = rootView.findViewById(R.id.quick_add_task_content_edt);
                                    etContent.setText(data.getTitle());
                                }
                            },
                            new QuickAddHolder(QuickAddHolder.QuickAddType.EVENT_UPDATE),
                            new QucikAddInputCheckRule(120, 2),
                            data.getFinish(),
                            new ExpansionCallback() {
                                @Override
                                public void onFinish(Context context, boolean isFinish, ChangeViewCallback changeViewCallback) {
                                    if (isFinish) {
                                        AlertUtils.showToast(context, "请指定事件完成时间");
                                        DatePickDialog dialog = new DatePickDialog(context);
                                        dialog.setYearLimt(5);
                                        dialog.setType(DateType.TYPE_ALL);
                                        dialog.setStartDate(new Date());
                                        dialog.setOnChangeLisener(null);
                                        dialog.setOnSureLisener(new OnSureLisener() {
                                            @Override
                                            public void onSure(Date finishDt) {
                                                ServiceFactory.getInstance().getEventService().doCreateTaskAndSetFinish(data.getId(), true, finishDt);
                                                changeViewCallback.onChangeView(true);
                                            }
                                        });
                                        dialog.show();
                                    } else {
                                        ServiceFactory.getInstance().getEventService().doCreateTaskAndSetFinish(data.getId(), false, null);
                                        changeViewCallback.onChangeView(true);
                                    }
                                }
                            }
                    );

                    break;
                case R.id.labScheduDt:
                    if (data != null && data.getId() != null) {
                        Task task = ServiceFactory.getInstance().getEventService().findEventTask(data.getId());
                        if (task != null) {
                            Intent intent = new Intent(view.getContext(), TaskDetailActivity.class);
                            intent.putExtra(TaskDetailActivity.PARAMS_KEY, task.getId());
                            ((Activity) getmContext()).startActivityForResult(intent, 1003);
                        }
                    }
                    break;
            }
        }

        @Override
        public void onItemSelected(Context context) {

        }

        @Override
        public void onItemClear(Context context) {

        }
    }

    // 头部内容
    public class HeadHolder extends RecyclerView.ViewHolder {
        public HeadHolder(View itemView) {
            super(itemView);
        }
    }

    // 尾部内容
    public class ButtomHolder extends RecyclerView.ViewHolder {
        public ButtomHolder(View itemView) {
            super(itemView);
        }
    }

    public interface RefreshEventCountCallback {
        void refresh();
    }

    public void setRefreshEventCountCallback(RefreshEventCountCallback refreshEventCountCallback) {
        CurriculumOrderAdapter.refreshEventCountCallback = refreshEventCountCallback;
    }
}
